import { defineStore } from 'pinia';

interface DictItem {
  key: string;
  value: any;
}

interface DictState {
  dict: DictItem[];
}

export const useDictStore = defineStore('dict', {
  state: (): DictState => ({
    dict: [],
  }),

  getters: {
    getDict: (state) => (key: string) => {
      return state.dict.find((item) => item.key === key)?.value;
    },
  },

  actions: {
    // 设置字典
    setDict(data: DictItem) {
      if (data.key !== null && data.key !== '') {
        this.dict.push({
          key: data.key,
          value: data.value,
        });
      }
    },

    // 删除字典
    removeDict(key: string) {
      try {
        for (let i = 0; i < this.dict.length; i++) {
          if (this.dict[i].key == key) {
            this.dict.splice(i, 1);
            return true;
          }
        }
      } catch (e) {
        console.error(e);
      }
    },

    // 清空字典
    cleanDict() {
      this.dict = [];
    },
  },
});

